package calao.client;

import com.google.gwt.user.client.ui.StackPanel;

/**
 * A composite that contains the shortcut stack panel on the left side.
 */
class ShortcutsPanel 
extends StackPanel 
{

	final Desktop desktop;

	int width = -1;
	int height = -1;

	/**
	 * Constructs a new shortcuts widget using the specified images.
	 * 
	 * @param images a bundle that provides the images for this widget
	 */
	public ShortcutsPanel(Desktop desktop) 
	{
		this.desktop = desktop;
		this.addStyleName("calao-ShortcutsPanel");
	}

	public void addShortcut(Shortcut shortcut) 
	{
		StringBuffer header = new StringBuffer();
		boolean isFirst = getChildren().size()==0;
		header.append("<div class=\"xtop");
		if (isFirst) header.append(" xfirst");
		header.append("\"><b class=\"xb1\"></b><b class=\"xb2\"></b><b class=\"xb3\"></b><b class=\"xb4\"></b></div>");
		header.append("<div class=\"xcont\">");
		if (shortcut.icon!=null) header.append(shortcut.icon.getHTML());
		header.append("<p>");
		header.append(shortcut.getTitle());
		header.append("</p></div>");
		add(shortcut, header.toString(), true);
	}

	void setHeight(int height)
	{
		if (this.height==height) return;
		desktop.log("Setting shortcuts panel height to "+height);
		this.height = height;
		if (getSelectedIndex()>=0) {
			getShortcut(getSelectedIndex()).setHeight(getShortcutHeight());
		}
		// now set global container height
		super.setHeight(""+height);
	}
	
	int getShortcutHeight()
	{
		int result = height - getWidgetCount() * getHeaderSize() - 1;
		desktop.log("Shortcut content height: "+result);
		return result;
	}
	
	int getHeaderSize()
	{
		if (!isAttached()) throw new RuntimeException();
		int viewIndex = getSelectedIndex();
		int viewTop = getChildren().get(viewIndex).getAbsoluteTop();
		int headerSize = (viewTop - getAbsoluteTop())/(viewIndex+1);
		desktop.log("Shortcut header size: "+headerSize);
		return headerSize;
	}

	void setWidth(int width)
	{
		if (this.width==width) return;
		desktop.log("Setting shortcuts panel width to "+width);
		this.width = width;
		if (getSelectedIndex()>=0) {
			getShortcut(getSelectedIndex()).setWidth(width);
		}
		// now set global container width
		super.setWidth(""+width);
	}
	
	Shortcut getShortcut(int index)
	{
		return (Shortcut)getWidget(index);
	}
	
	public void showStack(int index)
	{
		super.showStack(index);
		getShortcut(index).setSize(width, getShortcutHeight());
	}

}
